package com.cjj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cjj.common.convention.exception.ClientException;
import com.cjj.common.enums.CommentStatus;
import com.cjj.dao.entity.CommentLike;
import com.cjj.dao.entity.PostComment;
import com.cjj.dao.mapper.CommentLikeMapper;
import com.cjj.dao.mapper.PostCommentMapper;
import com.cjj.service.CommentLikeService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class CommentLikeServiceImpl extends ServiceImpl<CommentLikeMapper, CommentLike> implements CommentLikeService {

    private final CommentLikeMapper commentLikeMapper;
    private final PostCommentMapper postCommentMapper;

    /**
     * 点赞评论
     */
    @Transactional(rollbackFor = Exception.class)
    public void likeComment(Long commentId, Long userId) {
        // 检查评论是否存在
        PostComment comment = postCommentMapper.selectById(commentId);
        if (comment == null || !CommentStatus.PUBLISHED.getValue().equals(comment.getStatus())) {
            throw new ClientException("评论不存在或已删除");
        }

        // 检查是否已经点赞
        if (hasLiked(commentId, userId)) {
            throw new ClientException("已经点赞过该评论");
        }

        // 添加点赞记录
        CommentLike commentLike = new CommentLike()
                .setCommentId(commentId)
                .setUserId(userId);
        commentLikeMapper.insert(commentLike);

        // 更新评论点赞数
        updateCommentLikeCount(commentId, 1);
    }

    /**
     * 取消点赞评论
     */
    @Transactional(rollbackFor = Exception.class)
    public void unlikeComment(Long commentId, Long userId) {
        // 删除点赞记录
        LambdaQueryWrapper<CommentLike> wrapper = Wrappers.lambdaQuery(CommentLike.class)
                .eq(CommentLike::getCommentId, commentId)
                .eq(CommentLike::getUserId, userId);

        int deleteCount = commentLikeMapper.delete(wrapper);
        if (deleteCount > 0) {
            // 更新评论点赞数
            updateCommentLikeCount(commentId, -1);
        }
    }

    /**
     * 检查用户是否点赞过评论
     */
    public boolean hasLiked(Long commentId, Long userId) {
        LambdaQueryWrapper<CommentLike> wrapper = Wrappers.lambdaQuery(CommentLike.class)
                .eq(CommentLike::getCommentId, commentId)
                .eq(CommentLike::getUserId, userId);
        return commentLikeMapper.selectCount(wrapper) > 0;
    }

    /**
     * 批量检查用户点赞状态
     */
    public Map<Long, Boolean> batchCheckLikeStatus(List<Long> commentIds, Long userId) {
        if (commentIds == null || commentIds.isEmpty() || userId == null) {
            return new HashMap<>();
        }

        LambdaQueryWrapper<CommentLike> wrapper = Wrappers.lambdaQuery(CommentLike.class)
                .in(CommentLike::getCommentId, commentIds)
                .eq(CommentLike::getUserId, userId)
                .select(CommentLike::getCommentId);

        List<CommentLike> likes = commentLikeMapper.selectList(wrapper);
        Set<Long> likedCommentIds = likes.stream()
                .map(CommentLike::getCommentId)
                .collect(Collectors.toSet());

        // 构建结果Map
        Map<Long, Boolean> result = new HashMap<>();
        for (Long commentId : commentIds) {
            result.put(commentId, likedCommentIds.contains(commentId));
        }

        return result;
    }

    /**
     * 获取评论的点赞用户列表
     */
    public List<Long> getCommentLikes(Long commentId) {
        LambdaQueryWrapper<CommentLike> wrapper = Wrappers.lambdaQuery(CommentLike.class)
                .eq(CommentLike::getCommentId, commentId)
                .select(CommentLike::getUserId);

        return commentLikeMapper.selectList(wrapper)
                .stream()
                .map(CommentLike::getUserId)
                .collect(Collectors.toList());
    }

    /**
     * 更新评论点赞数
     */
    private void updateCommentLikeCount(Long commentId, int delta) {
        LambdaUpdateWrapper<PostComment> updateWrapper = Wrappers.lambdaUpdate(PostComment.class)
                .eq(PostComment::getCommentId, commentId)
                .setSql("like_count = like_count + " + delta);
        postCommentMapper.update(null, updateWrapper);
    }
}
